qui(
    function(require, exports, module) {

        Server.Grid = function(options) {
            this.dao = Server.Dao;
            this.config = Server.Config;
            this.util = Server.Util;
            this.options = options || {};
            this.construct = options.construct || function() {
                this.init();
            };
            this.construct.call(this);
        };

        Com.inherits(Server.Grid, Ancestor.Grid).extend({
            flag:0,
            init: function() {
                var self = this;
                var $container = self.options.$container;
                self.$grid = $container.find('table.grid');
                self.orderNum=[1,1,1,1,1,1,1];
                Server.Util.getClusterList(self.options.$container);
                self.perpareData();
                self.bindBasicEvent();
                self.initSuggest();
            },

            perpareData: function() {
                var self = this;
                var username = $("div.user a.name").html();
                Server.Util.setProvince();
            },

            bindBasicEvent: function() {
                var self = this;

                var $container = self.options.$container;

                $container.find('.query-add').click(function() {
					window.open("/epg/server_edit.html");
                });

                $container.find(".query-btn").on('click.query', function() {
                    //self.flag=0;
                    self.query(self.flag);
                    return false;
                });

                $container.find('.zzd-server').click(function(){
                    window.open("/epg/zzd_server.html");
                })

                $(document).keydown(function(e){
                    if(e.altKey && e.which==13){
                        if(self.flag==0){
                            self.flag=1
                        }else{
                            self.flag=0;
                        }
                        self.query(self.flag);
                        console.log(self.flag)
                    }
                })

                $container.find("select[name='monitor1']").change(function () {
                    if($(this).val()=='err'){
                        $container.find("select[name='monitor2']").show();
                    }else {
                        $container.find("select[name='monitor2']").hide();
                    }
                });

                $container.find("button[type='reset']").click(function(){
                    $container.find("select[name='monitor2']").hide();
                    $container.find("input[name='clusterId']").removeAttr('data-id');
                });
			},

			bindFormEvent: function($form) {
                var self = this;
			},
            jqLoadComplete:function(){
                var self=this;
                $(".ui-jqgrid-htable").eq(0).find('div').each(function(i,ele){
                    //指明可排序 位置
                    if(i>=11&&i<=17){
                        self.util.loadOrder('none',$(ele));
                        $(ele).find('span').eq(0).css('display','inline');
                    }
                });
                Server.Util.difMonitorNull();

            },

            run: function(options, callback) {
                var self = this;
                var gridConfig = self.getGridConfig();
                var id=location.search;
                var data={};
                if(id&&id!=""){
                    id = id.slice(1).split("=")[1];
                    data = {postData:{'id':id}};
                }
                options = $.extend(true, {
                    width: 1500,
                    shrinkToFit: false,
                    // idPrefix: 'Video-',
                    autowidth: false,
                    loadComplete:function(){
                        self.jqLoadComplete();
                        self.query(0);
                    },
                    
                    onSortCol:function(index,name){
                        var morder;
                        if(self.orderNum[name-11]%2==0){
                            morder='asc';
                        }else{
                            morder='desc';
                        }
                        self.$grid.setGridParam( {
                            sortorder:morder,
                            loadComplete:function(){
                                self.jqLoadComplete();
                                 var $ddiv=$(".ui-jqgrid-htable").eq(0).find('div').eq(name);
                                 self.util.loadOrder(morder,$ddiv);
                            }
                        }).trigger('reloadGrid', [{
                            page: 1,
                        }]);
                        self.orderNum[name-11]++;
                        return 'stop';
                    },
                }, gridConfig, options,data);

                self.$grid.jqGrid(options);



                var colModelConfig = Server.Config.TABLE_STATUS_COLMODEL_CONFIG;

                var tableConfig = $.extend(true, {}, Server.Config.TABLE_STATUS );
                tableConfig.width =  1500;
                var colModel = tableConfig.colModel;
                var newColModel = [];

                $.each(colModel, function(i, model) {
                    newColModel.push(colModelConfig[model]);
                });
                tableConfig.colModel = newColModel;
                $('#serverStatusList').jqGrid(tableConfig);
            },

            getParam: function() {
                var self = this;
                var $container = self.options.$container;

                var $grid = self.$grid;
                var params = {};
                var $form = $container.find('form[name="basicFrm"]');

                var $elements = $.makeArray($form.prop('elements')).filter(function(item) {
					return true;
                });

				var checkboxVal = [];
                var name;
                var key;
                var flag=0;
                $.each($elements, function() {
                    name = this.name;
                    if (name) {
						if(name=='monitor1')	{
                            if($(this).val()=='err'){
                                flag=1;
                            }
                            else{
                                params['monitor'] = $.trim($(this).val());
                            }
						}else if(name=='monitor2'&&flag==1){
                            params['monitor'] = $.trim($(this).val());
                        }else if(name == 'clusterId'){
                            params['cluster'] = $("input[name=clusterId]").suggest("getValue");
                        }else {
							if($(this).val()){
								params[name] = $.trim($(this).val());
							}
						}
                    }
                });
                return params;
            },

            query: function(flag) {
                var self = this;
                var $container = self.options.$container;
                var $grid = self.$grid;
                self.overridePostData($grid);
                var params = self.getParam();

                if(flag==0){
                    $grid.jqGrid('setGridParam', {
                        postData: params,
                        width: 1350,
                        sortorder:'none',
                        loadComplete:function(){
                            self.jqLoadComplete();
                        },
                    }).hideCol(["load","dataFreePer","allFreePer","availableMemPer","freeSwapPer","inIcmploss","outIcmploss"]).trigger('reloadGrid', [{
                        page: 1,
                    }]);
                }

                if(flag==1){
                    $grid.jqGrid('setGridParam', {
                        postData: params,
                        width: 1900,
                        sortorder:'none',
                        loadComplete:function(){
                            self.jqLoadComplete();
                        },
                    }).showCol(["load","dataFreePer","allFreePer","availableMemPer","freeSwapPer","inIcmploss","outIcmploss"]).trigger('reloadGrid', [{
                        page: 1,
                    }]);
                }

            },

            initSuggest: function () {
                var self = this;
                var ClusterSuggest = {
                    options: {
                        ajaxSettings: {
                            beforeSend: function (request) {
                                var authBase = Ancestor.Util.getAuth("/sginal/server/clusterList");
                                request.setRequestHeader('Sign', authBase.sign);
                                request.setRequestHeader("Time", authBase.clientTime);
                                request.setRequestHeader("From", authBase.from);
                                request.setRequestHeader("UserName", (auth.baseInfo.authInfo == null) ? "" : escape(auth.baseInfo.authInfo.userName).toLocaleLowerCase().replace(/%u/gi, '\\u'));
                            }
                        },
                        select: function (event, object) {
                            var obj = { "clusterName": Number(object.item.id) };
                            // Record.Dao.getColList({paramsObj: JSON.stringify(obj), dataMode: "simple", pageSize: 100}, function (retData) {
                            //     Server.Util.fillRelationColSelect(retData);
                            // })
                            return true;
                        },
                        source: "/api/sginal/server/clusterList",
                        method: "post",
                        autoFilter: false,
                        autoFocus: false,
                        multiple: false,
                        parseValue: function () {
                            var val = this.element.val(),
                                ret = []
                            return ret;
                        },
                        getParam: function (term) {
                            return { "clusterName": $.trim(term) }
                        },
                        process: function (json) {
                            var ret = [],
                                self = this,
                                options = self.options,
                                itemData = null;
                            var data = null;
                            if (json == null) {
                                return [];
                            }
                            if (json.code === "A00000") {
                                data = json.data == null ? null : json.data;
                            }
                            if (!data) {
                                return [];
                            }
                            $.map(data.result, function (item) {
                                itemData = {};
                                itemData[options.valueKey] = item["id"];
                                itemData[options.labelKey] = item["name"]
                                ret.push(itemData);
                            });
                            return ret;
                        },
                        template: function (item) {
                            return item.label;
                        }
                    }
                }
                $("input[name=clusterId]").suggest(ClusterSuggest.options);
            }

        });

    }
);